package cn.johnyu.util;


import cn.johnyu.domain.Account;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 只是用于展示Gson的使用方法
 */
public class GsonDemo {
    public static void main(String[] args) {

        // 创建一个自定义的TypeAdapter
        TypeAdapter<GrantedAuthority> grantedAuthorityTypeAdapter = new TypeAdapter<>() {
            @Override
            public void write(JsonWriter out, GrantedAuthority value) throws IOException {
                out.value(value.getAuthority());
            }

            @Override
            public GrantedAuthority read(JsonReader in) throws IOException {
                return new SimpleGrantedAuthority(in.nextString());
            }
        };


        // 创建一个Gson实例，并注册自定义的TypeAdapter
        Gson gson = new GsonBuilder()
//                .registerTypeAdapter(GrantedAuthority.class, grantedAuthorityTypeAdapter)
                .create();

        // 创建一个DomainUser对象
        List<GrantedAuthority> authorities = Arrays.asList(
                new SimpleGrantedAuthority("ROLE_ADMIN"),
                new SimpleGrantedAuthority("ROLE_USER")
        );
        Account account=new Account("1","John","password",List.of("ROLE_ADMIN","ROLE_USER"));


        // 将DomainUser对象转换为JSON字符串
        String json = gson.toJson(account);
        System.out.println(json);  // 输出：{"id":1,"username":"John","password":"password","enabled":true,"authorities":[{"authority":"ROLE_ADMIN"},{"authority":"ROLE_USER"}]}

        // 将JSON字符串转换回DomainUser对象
        Account account1 = gson.fromJson(json, Account.class);
        System.out.println(account1);  // 输出

    }
}